package com.ctgu.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ctgu.common.ResponseResult;
import com.ctgu.model.entity.*;
import com.ctgu.mapper.CompanyMapper;
import com.ctgu.service.ICompanyService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ctgu.service.IEvaluateService;
import com.ctgu.service.IPositionService;
import com.ctgu.utils.ExcelUtil;
import com.ctgu.utils.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author yiMa
 * @since 2023-07-05
 */
@Service
public class CompanyServiceImpl extends ServiceImpl<CompanyMapper, Company> implements ICompanyService {

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private EmployeeServiceImpl employeeService;

    @Autowired
    private IPositionService positionService;

    @Autowired
    private ExperienceServiceImpl experienceService;

    @Autowired
    private IEvaluateService evaluateService;

    @Override
    public ResponseResult getCompanyOne(Integer id) {
        if(id==null){
            return new ResponseResult<>(200,"成功", SecurityContextHolder.getContext().getAuthentication());
        }
        return new ResponseResult(200,"成功",getById(id));
    }

    @Override
    public ResponseResult getList(int page, int pageSize, String name) {
        //分页构造器
        Page pageInfo=new Page(page,pageSize);
        //构造条件构造器
        LambdaQueryWrapper<Company> queryWrapper=new LambdaQueryWrapper();
        //添加过滤条件
        queryWrapper.like(StringUtils.isNotEmpty(name),Company::getCompanyName,name);
        //添加排序条件
        queryWrapper.orderByAsc(Company::getStatus);
        queryWrapper.notIn(Company::getId,-1);
        //执行查询
        this.page(pageInfo,queryWrapper);
        return new ResponseResult<>(200,"分页成功",pageInfo);
    }

    @Override
    public ResponseResult register(Company company) {
        LambdaQueryWrapper<Company> wrapper=new LambdaQueryWrapper<>();
        wrapper.eq(Company::getCompanyName,company.getCompanyName());
        Company one = getOne(wrapper);
        if(Objects.nonNull(one)){
            return new ResponseResult<>(400,"公司名已经存在重新输入");
        }
        wrapper=new LambdaQueryWrapper<>();
        wrapper.eq(Company::getUserName,company.getUserName());
        one=getOne(wrapper);
        if(Objects.nonNull(one)){
            return new ResponseResult<>(400,"用户名已经存在重新输入");
        }
        wrapper=new LambdaQueryWrapper<>();
        wrapper.eq(Company::getEmail,company.getEmail());
        one=getOne(wrapper);
        if(Objects.nonNull(one)){
            return new ResponseResult<>(400,"邮箱已注册重新输入");
        }
       company.setPassword(passwordEncoder.encode(company.getPassword()));
        save(company);
        return new ResponseResult<>(200,"注册成功，请等待管理员审核");
    }

    //更新公司信息
    @Override
    public ResponseResult updateInfo(Company company){
        LoginUser loginUser=(LoginUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        int id=loginUser.getUser().getId();
        Company company1 = getById(id);

        if(!company1.getUserName().equals(company.getUserName())){
            LambdaQueryWrapper<Company> wrapper=new LambdaQueryWrapper<>();
            wrapper.eq(Company::getUserName,company.getUserName());
            Company one = getOne(wrapper);
            if(Objects.nonNull(one)){
                return new ResponseResult<>(400,"用户名已经存在重新输入");
            }
        }
        if(!company1.getCompanyName().equals(company.getCompanyName())){
            LambdaQueryWrapper<Company> wrapper1=new LambdaQueryWrapper<>();
            wrapper1.eq(Company::getCompanyName,company.getCompanyName());
            Company one = getOne(wrapper1);
            if(Objects.nonNull(one)){
                return new ResponseResult<>(400,"公司名已经存在重新输入");
            }
        }
        final CopyOptions copyOptions = CopyOptions.create();
        copyOptions.setOverride(false);
        copyOptions.setIgnoreNullValue(true);
        BeanUtil.copyProperties(company1,company,copyOptions);
        updateById(company);
        return new ResponseResult<>(200,"更新成功",company);
//        QueryWrapper userName_wrapper = new QueryWrapper<>();
//        userName_wrapper.eq("user_name",company.getUserName());
//        userName_wrapper.ne("id",company.getId());
//        if(this.getOne(userName_wrapper) != null){
//            return new ResponseResult<>(400,"该用户名已被注册");
//        }
//
//        QueryWrapper phone_wrapper = new QueryWrapper<>();
//        phone_wrapper.eq("company_phone",company.getCompanyPhone());
//        phone_wrapper.ne("id",company.getId());
//        if(this.getOne(phone_wrapper) != null){
//            return new ResponseResult<>(400,"该电话号码已被注册");
//        }
//        QueryWrapper email_wrapper = new QueryWrapper<>();
//        email_wrapper.eq("user_name",company.getEmail());
//        email_wrapper.ne("id",company.getId());
//        if(this.getOne(email_wrapper) != null){
//            return new ResponseResult<>(400,"该邮箱已被注册");
//        }
//
//        QueryWrapper updateWrapper = new QueryWrapper<>();
//        updateWrapper.eq("id",company.getId());
//        this.update(company,updateWrapper);
//        return new ResponseResult<>(200,"更新成功");
    }

    @Override
    @Transactional
    public ResponseResult setEmpState(Integer[] ids) {
        //设置就职状态
        List<Employee> list = employeeService.listByIds(Arrays.asList(ids));
        //判断是否是该公司
        LoginUser loginUser=(LoginUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        Integer companyId = loginUser.getUser().getId();
        if(!companyId.equals(list.get(0).getCompanyId())){
            return new ResponseResult<>(400,"操作失败，请登入对应公司操作");
        }
        list=list.stream().map(item->{
            item.setWorkState("离职");
            item.setBeginDate(null);
            item.setCompanyId(-1);
            return item;
        }).collect(Collectors.toList());
        employeeService.updateBatchById(list);
        //更新该员工经历表
        LambdaUpdateWrapper<Experience> wrapper=new LambdaUpdateWrapper<>();
        wrapper.in(Experience::getEId,ids);
        wrapper.set(Experience::getTerminationDate,LocalDateTime.now());
        experienceService.update(wrapper);
//        String key="employee"+"-"+companyId+"-"+empById.getDepId();
//        redisCache.deleteObject(key);
        return new ResponseResult<>(200,"离职成功");
    }

    @Override
    public ResponseResult evaluate(Evaluate evaluate) {
        Employee empById = employeeService.getEmpById(evaluate.getE_id());
        if(Objects.isNull(empById)){
            return new ResponseResult<>(400,"评价失败，无该id员工");
        }
        //判断是否是该公司
        LoginUser loginUser=(LoginUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        Integer companyId = loginUser.getUser().getId();
        if(!companyId.equals(empById.getCompanyId())){
            return new ResponseResult<>(400,"操作失败，请登入对应公司操作");
        }
        Company company=(Company) loginUser.getUser();
        evaluate.setCompanyName(company.getCompanyName());
        evaluate.setTime(LocalDateTime.now());
        evaluateService.save(evaluate);
        return new ResponseResult<>(200,"评价成功");
    }

    @Override
    public ResponseResult uploadExcel(MultipartFile file) {
        try {
            List<Employee> list = ExcelUtil.readExcel(file);
            LoginUser loginUser=(LoginUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            Company company=(Company) loginUser.getUser();
            for (Employee employee: list) {
                employeeService.save(employee);
                Experience experience=new Experience();
                experience.setDateOfEmployment(LocalDateTime.now());
                experience.setEId(employee.getId());
                Position position = positionService.getById(employee.getPosId());
                experience.setDuties(position.getName());
                experience.setCompanyName(company.getCompanyName());
                experience.setWorkAddr(company.getCompanyAddr());
                experienceService.save(experience);
//                String key="employee"+"-"+company.getId()+"-"+employee.getDepId();
//                redisCache.deleteObject(key);
            }

            return new ResponseResult(200,"成功");
        } catch (IOException e){
            e.printStackTrace();
            return new ResponseResult(400,"失败");
        }
    }


}
